package cn.iocoder.yudao.module.fengdong.smartelderly.rabbitmq;

import cn.iocoder.yudao.module.fengdong.smartelderly.controller.admin.billing.vo.BillingCreateReqVO;
import cn.iocoder.yudao.module.fengdong.smartelderly.controller.admin.dayconfig.vo.DayconfigByTenantId;
import cn.iocoder.yudao.module.fengdong.smartelderly.convert.billing.BillingConvert;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.dataobject.billing.BillingDO;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.dataobject.oldman.OldmanDO;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.mysql.billing.BillingMapper;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.mysql.oldman.OldmanMapper;
import cn.iocoder.yudao.module.fengdong.smartelderly.utils.JsonUtils;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setTenantId;

/**
 * @author zhangjiasong
 * @description: TODO
 * @date 2023/12/19 14:56
 */
@Slf4j
@Component
public class DayconfigMq {
    @Resource
    private OldmanMapper oldmanMapper;
    @Resource
    private BillingMapper billingMapper;

    /**
     *  租户配置处理
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("DayconfigMqQueue"),
            exchange = @Exchange("myDayconfigMqExchange")
    ))
    @Transactional(rollbackFor = Exception.class)
    public void receive(Message message) throws UnsupportedEncodingException {
        log.info("缴费配置 = {}" ,  message);
        String tenantId = message.getMessageProperties().getHeader("tenant-id");
        String execute = message.getMessageProperties().getHeader("execute");
        if (message.getBody()==null && StringUtil.isNotBlank(tenantId)) {
            return;
        }
        setTenantId(Long.valueOf(tenantId));
        String msg=new String(message.getBody(),"UTF-8");
        //缴费配置
        DayconfigByTenantId dayconfigByTenantId = JsonUtils.jsonToObj(msg, DayconfigByTenantId.class);
        //老人管理信息
        List<OldmanDO> oldmanDOList =oldmanMapper.selectListByTenantId(dayconfigByTenantId.getTenantId());
        // 如果没有老人信息则进行处理
        if (oldmanDOList.isEmpty()) {
            return;
        }

        //判断配置信息 (当月是否有这一天 【有则正常处理 没有则取最后一天】)
        Calendar calendar = Calendar.getInstance();

        BillingCreateReqVO billingCreateReqVO = new BillingCreateReqVO();
        billingCreateReqVO.setType(dayconfigByTenantId.getType());
        billingCreateReqVO.setTitle(dayconfigByTenantId.getTitle());
        billingCreateReqVO.setStartTime(LocalDateTime.now());
        billingCreateReqVO.setContent(dayconfigByTenantId.getContent());
        billingCreateReqVO.setMoney(dayconfigByTenantId.getMoney());

        if (calendar.getActualMaximum(Calendar.DAY_OF_MONTH) >= dayconfigByTenantId.getDay()) {
            //这月有这天
            LocalDate currentDate = LocalDate.now();
            LocalDate targetDate = currentDate.withDayOfMonth(Math.toIntExact(dayconfigByTenantId.getDay()));
            LocalDateTime targetDateTime = targetDate.atStartOfDay();
            log.info("订单结束时间 = {}" , targetDateTime );
            billingCreateReqVO.setEndTime(targetDateTime);
        } else {
            //否则 取最后一天
            LocalDate currentDate = LocalDate.now();
            LocalDate lastDayOfMonth = currentDate.withDayOfMonth(currentDate.lengthOfMonth());
            LocalDateTime endOfMonth = lastDayOfMonth.atStartOfDay();
            log.info("该月没有这一天(取该月最后一天)--订单结束时间 = {}" , endOfMonth );
            billingCreateReqVO.setEndTime(endOfMonth);
        }

        List<BillingDO> billingCreateReqVOS=new ArrayList<>();
        for (int i = oldmanDOList.size() - 1; i >= 0; i--) {
            //老人信息
            OldmanDO oldmanDO = oldmanDOList.get(i);

            BillingCreateReqVO billingReqVO = new BillingCreateReqVO();
            BeanUtils.copyProperties(billingCreateReqVO,billingReqVO);
            billingReqVO.setOldmanId(oldmanDO.getId());
            billingReqVO.setOldmanName(oldmanDO.getName());
            billingReqVO.setOldmanCard(oldmanDO.getIdentityCard());
            //查询今年该月份生成缴费单数量(oldmanId 不为空则查询该“长者”的缴费单数量)
            if(null==execute && billingMapper.selectBillingExist(billingReqVO)>0) {
                continue;
            }
            BillingDO billingDO=BillingConvert.INSTANCE.convert(billingReqVO);
            billingCreateReqVOS.add(billingDO);
        }
        //批量添加缴费记录
        billingMapper.insertBatch(billingCreateReqVOS);
        log.info("老人数量 =" + billingCreateReqVOS.size() );
    }
}
